using System;
using System.IO;
using System.Security.Cryptography;
using Universe.IoC;

namespace Universe.WCF.Behaviors.WcfStreaming
{
    public class AdapterEnvironment
    {
        public static readonly ConfigurationContainer Default;

        static AdapterEnvironment()
        {
            Default = new ConfigurationContainer();
            Default.Register<HashAlgorithm>(() => MD5.Create());
            Default.Register<int>(() => 1024);
            var dir = GetDefaultBufferPath();
            if (dir != null)
                Default.Register<DirectoryInfo>(() => new DirectoryInfo(dir));

            Default.Register<IResponseStatusStorage>(() => new WebCacheResponseStatusStorage());
        }

        public static void Validate(ConfigurationContainer config)
        {
            config.ResolveRequired<HashAlgorithm>();
            config.ResolveRequired<DirectoryInfo>();
            config.ResolveRequired<IResponseStatusStorage>();
            config.ResolveRequired<int>();
        }



        static string GetDefaultBufferPath()
        {
            string[] tries = new[]
            {
                Environment.GetEnvironmentVariable("TEMP"),
                Environment.SystemDirectory.Substring(0, 2) + "\\Temp\\Streaming Buffer",
                Environment.GetEnvironmentVariable("TMP"),
            };

            foreach (var p in tries)
            {
                string d = new DirectoryInfo(p).FullName;
                try
                {
                    Directory.CreateDirectory(d);
                }
                catch (Exception)
                {
                }

                if (Directory.Exists(d))
                {
                    return d;
                }
            }

            return null;
        }
    }
}